package com.xjnt.base.support.admin.controller;

import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.xjnt.base.support.admin.entity.Account;
import com.xjnt.base.support.admin.entity.Group;
import com.xjnt.base.support.admin.entity.Role;
import com.xjnt.base.support.admin.entity.User;
import com.xjnt.base.support.admin.service.AccountService;
import com.xjnt.base.support.admin.service.GroupService;
import com.xjnt.base.support.admin.service.UserService;
import com.xjnt.frameworks.annotation.AutoInject;
import com.xjnt.frameworks.annotation.Router;
import com.xjnt.frameworks.core.CRUDController;
import com.xjnt.frameworks.exception.BusinessException;
import com.xjnt.frameworks.web.message.RetMsg;

@Router(name = "/system/admin/account", view = "admin/account")
public class AccountController extends CRUDController<Account, AccountService> {

	@AutoInject
	private AccountService accountService;

	@AutoInject
	private UserService userService;
	
	@AutoInject
	private GroupService groupService;

	@Override
	protected String getBizName() {
		return "用户账号";
	}
	
	@Override
	protected Class<Account> getClazz() {
		return Account.class;
	}

	@Override
	protected AccountService getService() {
		return accountService;
	}

	@Override
	public void doSave() {
		RetMsg retMsg = new RetMsg();
		try {
			Account model = getModel(getClazz());
			// 新增用户时初始化密码
			model.set(Account.PASSWORD, HashKit.md5("123456"));
			model.set(Account.SUPER, 0);
			model.set(Account.LOCKED, 0);
			User user = new User(); // 初始化关联一个空用户资料
			userService.save(user);
			model.set(Account.FK_USERID, user.getStr(User.PK_ID));
			boolean flag = getService().save(model);
			if (flag) {
				retMsg.pushOk("保存成功");
			} else {
				retMsg.pushError("保存失败");
			}
			renderJson(retMsg);
		} catch (Exception e) {
			throw new BusinessException("保存" + getBizName(), "发生异常：", e);
		}
	}

	public void lock() {
		RetMsg retMsg = new RetMsg();
		try {
			String uuid = getPara("id");
			if (StrKit.notBlank(uuid)) {
				Account account = new Account();
				account.set(Account.PK_ID, uuid);
				account.set(Account.LOCKED, 1);
				boolean flag = getService().update(account);
				if (flag) {
					retMsg.pushOk("锁定成功");
				} else {
					retMsg.pushError("锁定失败");
				}
			} else {
				retMsg.pushError("没有传递账号标识，无法进行操作");
			}
			renderJson(retMsg);
		} catch (Exception e) {
			throw new BusinessException("锁定" + getBizName(), "发生异常：", e);
		}
	}

	public void unlock() {
		RetMsg retMsg = new RetMsg();
		try {
			String uuid = getPara("id");
			if (StrKit.notBlank(uuid)) {
				Account account = new Account();
				account.set(Account.PK_ID, uuid);
				account.set(Account.LOCKED, 0);
				boolean flag = getService().update(account);
				if (flag) {
					retMsg.pushOk("解锁成功");
				} else {
					retMsg.pushError("解锁失败");
				}
			} else {
				retMsg.pushError("没有传递账号标识，无法进行操作");
			}
			renderJson(retMsg);
		} catch (Exception e) {
			throw new BusinessException("解锁" + getBizName(), "发生异常：", e);
		}
	}

	public void editUser() {
		String userid = getPara("userid");
		User user = userService.findById(userid);
		setAttr("user", user);
		render("user.html");
	}

	public void updUser() {
		RetMsg retMsg = new RetMsg();
		try {
			User user = getModel(User.class);
			boolean flag = userService.update(user);
			if(flag){
				retMsg.pushOk("保存资料成功");
			}else{
				retMsg.pushOk("保存资料失败");
			}
			renderJson(retMsg);
		} catch (Exception e) {
			throw new BusinessException("保存用户资料", "发生异常：", e);
		}
	}
	
	/**
	 * 分配用户组
	 */
	public void allocGroup(){
		//参数保持传递
		keepPara();
		// 登陆状态才能进行分配，则先获取登陆用户所拥有的用户组。
		Account account = (Account) getCurrUser();
		List<Group> userGroups = Lists.newArrayList();
		if(account.getInt(Account.SUPER) == 1){ //超级管理员
			userGroups = groupService.findAll();
		} else { //隶属机构下的所有组
			String orgId = account.getStr(Account.FK_ORGID);
			userGroups = groupService.findByOrgId(orgId);
		}
		// 页面传递的目标分配用户ID
		String accountId = getPara("accountId");
		List<Group> targetUserGroups = groupService.findByAccountId(accountId);
		// 求并集
		userGroups.removeAll(targetUserGroups);
		userGroups.addAll(targetUserGroups);
		List<Map<String, String>> finalGroups = Lists.newArrayList();
		for (Group group : userGroups) {
			Map<String, String> finalGroup = Maps.newHashMap();
			finalGroup.put("name", group.getStr(Role.NAME));
			finalGroup.put("val", group.getStr(Role.PK_ID));
			if(targetUserGroups.contains(group)){
				finalGroup.put("selected", "selected");
			}
			finalGroups.add(finalGroup);
		}
		setAttr("allocGroup", finalGroups);
		render("allocGroup.html");
	}
	
	/**
	 * 保存分配用户组
	 */
	public void doAllocGroup(){
		RetMsg retMsg = new RetMsg();
		try{
			// 获得页面分配的用户组标识集合
			String[] groupIds = getPara("allocGroupIds") == null ? null : getPara("allocGroupIds").split(",");
			if(null != groupIds){ //用户组标识集合不为空
				List<Group> newUserGroups = groupService.findByIds(groupIds);
				// 页面传递的目标分配用户ID
				String accountId = getPara("accountId");
				List<Group> originalUserGroups = groupService.findByAccountId(accountId);
				// 定义原用户组与新用户组的交集
				List<Group> retainGroups = Lists.newArrayList();
				retainGroups.addAll(originalUserGroups);
				retainGroups.retainAll(newUserGroups);
				// 从新的用户组中去掉原来已增加过的用户组
				newUserGroups.removeAll(retainGroups);
				// 原用户组中去掉交集用户组，就是需要删除的用户组
				originalUserGroups.removeAll(retainGroups);
				
				if(!originalUserGroups.isEmpty()){
					getService().removeGroups(accountId, originalUserGroups);
				}
				// 保存新分配的用户组关系
				if(!newUserGroups.isEmpty()){
					getService().allocGroups(accountId, newUserGroups);
				}
				
			} else { //用户组集合为null时，删除该用户与所有用户组的关系
				String accountId = getPara("AccountId");
				groupService.removeAllAccount(accountId);
			}
			retMsg.pushOk("分配用户组成功");
			renderJson(retMsg);
		} catch (Exception ex){
			throw new BusinessException("用户分配用户组", "发生异常：", ex);
		}
	}
}
